<?php


namespace support\utils;


use ArrayAccess;

class Form  implements ArrayAccess
{
    public $params = [];

    public function __construct($params = [])
    {
        $this->params = array_merge($this->params, $params);
    }

    static function getForm($params)
    {
        return new Form($params);
    }


    /**
     * @return int
     */
    public function getPage()
    {
        return intval($this->params['pageNo'] ?? 1);
    }

    /**
     * @return int
     */
    public function getOffset()
    {
        return (intval($this->params['pageNo'] ?? 1) - 1) * $this->getPageSize();
    }

    /**
     * @return int
     */
    public function getPageSize()
    {
        return intval($this->params['pageSize'] ?? 10);
    }

    public function offsetExists($offset)
    {
        return isset($this->params[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->params[$offset] ?? null;
    }

    public function offsetSet($offset, $value)
    {
        $this->params[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->params[$offset]);
    }

    /**
     * @param string $default
     * @return string
     */
    public function getSortField($default = "")
    {
        return $this->params['sort_field'] ?? $default;
    }

    /**
     * @param string $default
     * @return string
     */
    public function getOrder($default = "")
    {
        return $this->params['order'] ?? $default;
    }

    /**
     * @param string $default
     * @return string
     */
    public function getQueryOrder($default = SORT_ASC)
    {
        $map = [
            'asc' => SORT_ASC,
            'desc' => SORT_DESC,
        ];
        return $map[$this->params['order']] ?? $default;
    }
}